from django.conf import settings
from fdfs_client.client import Fdfs_client, os
from rest_framework import serializers
from goods.models import SPUSpecification,SPU,SKUImage, SKU


class SKUImageSerializer(serializers.ModelSerializer):


    class Meta:
        model = SKUImage
        fields= ('id','sku','image')


    def create(self, validated_data):
        # 生成连接fastdfs对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR,'utils/fastdfs/client.conf'))
        # 获取图片数据
        image = validated_data['image']
        # 以二进制数据上传
        res = client.upload_by_buffer(image.read())
        if res['Status'] !='Upload successed.':
            raise serializers.ValidationError('上传失败')
        # 保存链接
        image_path = res['Remote file_id']
        sku = validated_data['sku']
        img = SKUImage.objects.create(sku=sku,image=image_path)

        sku.default_image = image_path
        sku.save()
        return img

    def update(self, instance, validated_data):
        # 生成连接fastdfs对象
        client = Fdfs_client(os.path.join(settings.BASE_DIR, 'utils/fastdfs/client.conf'))
        # 获取图片数据
        image = validated_data['image']
        # 以二进制数据上传
        res = client.upload_by_buffer(image.read())
        if res['Status'] !='Upload successed.':
            raise serializers.ValidationError('上传失败')
        # 保存链接
        image_path = res['Remote file_id']
        instance.image = image_path
        instance.save()
        instance.sku.default_image=image_path
        instance.sku.save()
        return instance





class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id','name')

